/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;


import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import po.Organization;
import po.User;
import java.util.List;
import java.util.Set;
import myUtils.Constants;
import myUtils.page.Result;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author sony
 */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

    public static int USERUNCHECHED = 0;
    public static int USERCHECHED = 1;
    public static int USERMANAGER = 2;
    private SessionFactory _sessions;

    public void save(User user) throws Exception {
        getHibernateTemplate().save(user);
    }

    public User getUser(int userId) {
        return (User) getHibernateTemplate().get(User.class, userId);
    }

    public List getOrgsJoined(int userId) {
        String query =  "Select r.organization from Userorgrelation as r  where r.state=1 and r.user.id ="+ userId;


        return (List) getHibernateTemplate().find(query);
    }

    public List getOrgsLeaded(int userId) {
        //String query = "SELECT Organization.id,Organization.name,Organization.date,Organization.type,Organization.description,Organization.department FROM (Userorgrelation where user_id=" + userId + " and state=2) natural join Organization";
        String query = "Select r.organization from Userorgrelation as r  where r.state=2 and r.user.id =" + userId;
        return (List) getHibernateTemplate().find(query);
    }

    public List getNews(int userId) {
        String query="select n from Userorgrelation as r, News as n where n.organization.id=r.organization.id and r.user.id="+userId+" order by n.time DESC";
        //String query = "Select  r.organization.newses from Userorgrelation as r where r.user.id=" + userId ;
        return (List) getHibernateTemplate().find(query);
    }

    public List getMyNews(int userId) {
        String query="select n from Userorgrelation as r, News as n where n.organization.id=r.organization.id and r.state=2 and r.user.id="+userId+" order by n.time DESC";
        return (List) getHibernateTemplate().find(query);
    }
    public List getUnreadMails(int userId){
        String query = "Select m from Mail as m where m.userByToId.id="+userId+" and m.isread in (0,3) order by m.time DESC";
        return (List) getHibernateTemplate().find(query);
    }
    public Result getMyNews(int userId,int page){
        
         /*Page p=PageUtil.createPage(page, tempList.size());
         int to=page*p.getEveryPage()>=tempList.size()?tempList.size():page*p.getEveryPage();
         return new Result(p,tempList.subList((p.getCurrentPage()-1)*p.getEveryPage(), to));*/
         return new Result(page,getMyNews(userId));
    }

    public Result getNews(int userId, int page) {
        return new Result(page,getNews(userId));
    }
}
